package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	Code  string `gorm:"index"` //Code: 编号
	Price uint   // Price:价格，单位分
}

func main() {
	dsn := "root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	// 自动维护表结构
	db.AutoMigrate(&Product{})

	// 新增记录
	db.Create(&Product{
		Code:  "gk123",
		Price: 12,
	})

	// 查询记录
	var product Product
	db.First(&product)
	fmt.Println(product)
	db.First(&product, "code = ?", "gk123")
	fmt.Println(product)
	db.First(&product, "code = ?", "dad")
	fmt.Println(product)
}
